package com.huaxingbankas.modules.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.huaxingbankas.modules.dao.UsersDAO;
import com.huaxingbankas.modules.model.Users;

public class MyUserDetailService<GrantedAuthority> implements UserDetailsService {

	//private SecurityContextHolder s= new SecurityContextHolder();
	private UsersDAO usersdao;
	@Resource
	public void setUsersdao(UsersDAO usersdao) {
		this.usersdao = usersdao;
	}

	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		ArrayList<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
		if (StringUtils.isEmpty(username))
			throw new UsernameNotFoundException("username is null!");

		
		List<Users> ulist = (List<Users>) this.usersdao.find(1);
		if (ulist.size() > 0)
		{
			Users u = ulist.get(0);
//			List<Role> rlist = (List<Role>) this.userDAO.findListBySQLQuery("SELECT a.roleName FROM dbo.role a INNER JOIN groupRole c ON a.roleId = c.roleId INNER JOIN dbo.groups b ON c.groupID = b.groupID inner join dbo.groupUser d on	b.groupId=d.groupID inner join dbo.users e on d.userid=e.userid WHERE (e.userName = '"
//					+ username + "')",
//					Role.class);
//			for (Role role : rlist)
//			{
//				auths.add(new GrantedAuthorityImpl(role.getRoleName()));
//			}
//			// User(String username, String password, boolean enabled, boolean accountNonExpired,
//			// boolean credentialsNonExpired, boolean accountNonLocked, Collection<GrantedAuthority> authorities) {
			auths.add((GrantedAuthority) new GrantedAuthorityImpl("ROLE_USER"));
			auths.add((GrantedAuthority) new GrantedAuthorityImpl("ROLE_ADMIN"));
			User user=new User(username, u.getPassword(), "1".equals(u.getEnabled())?true:false, u.getExpiredate().compareTo((new Date()))>0?true:false, true, true,(Collection)auths);
			return user;
		}
		else
		{
			throw new UsernameNotFoundException("username is not found!");
		}
	}

}
